'use strict';

// Definition for singly-linked list.
function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
  // 创建一个虚拟头节点
  let dummy = new ListNode(0);
  dummy.next = head;
  let prevNode = dummy;

  // 遍历链表，交换相邻节点
  while (prevNode.next !== null && prevNode.next.next !== null) {
    let firstNode = prevNode.next;
    let secondNode = prevNode.next.next;

    // 交换节点
    firstNode.next = secondNode.next;
    secondNode.next = firstNode;
    prevNode.next = secondNode;

    // 更新指针
    prevNode = firstNode;
  }

  // 返回新的头节点
  return dummy.next;
};

let head = new ListNode(1);
let curNode = head;
for (let i = 2; i <= 4; i++) {
  curNode.next = new ListNode(i);
  curNode = curNode.next;
}

head = swapPairs(head);
